<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具条 -->
      <PageTools>
        <!-- 老语法 -->
        <!-- <div slot="before">123123</div> -->
        <!-- 新语法 -->
        <!-- <template v-slot:before>123123</template> -->
        <template #before>共计{{ page.total }}条员工信息</template>

        <el-button type="primary" :disabled="!checkPermission('employees-import')" size="small" @click="$router.push('/import')">导入</el-button>
        <el-button type="primary" :disabled="!checkPermission('employees-export')" size="small" @click="exportData">导出全部</el-button>
        <el-button type="success" size="small" :disabled="checkArr.length===0 || !checkPermission('employees-export')" @click="exportCheckData">导出选中</el-button>
        <el-button type="primary" :disabled="!checkPermission('employees-add')" size="small" @click="$refs['add-employee'].showDialog=true">新增员工</el-button>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list" @selection-change="checkArr=$event">
          <el-table-column type="selection" />
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" sortable="">
            <template slot-scope="{row}">
              <img
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                :src="row.staffPhoto"
                alt=""
                @click="showImg(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formOfEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template slot-scope="{row}">
              <span>{{ row.timeOfEntry | formatDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" :disabled="!checkPermission('employees-edit')" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showDialogSetting(row)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('employees-del')" @click="delRow(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 分页组件 -->
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[10, 30, 40, 50]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          background
          @size-change="sizeChange"
          @current-change="currentChange"
        />

      </el-card>
    </div>
    <!-- 新增修改的弹框 -->
    <AddEmployee ref="add-employee" @update-list="getEmployeeList" />
    <!-- 预览图片二维码 -->
    <el-dialog
      title="预览"
      :visible.sync="showCode"
      width="30%"
    >
      <canvas ref="canvas" />
    </el-dialog>

    <!-- 用户关联角色 -->
    <AssignRole ref="assgin-role" />

  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import QRCode from 'qrcode'
export default {
  name: 'Employess',
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      page: {
        page: 1, // 页码
        size: 10, // 每页数量
        total: 0
      },
      list: [],
      checkArr: [],
      showCode: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表的方法
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
    },
    // 每页数量更换
    sizeChange(val) {
      this.page.size = val
      this.getEmployeeList()
    },
    // 页码更换事件
    currentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formOfEmployment(row, column, cellValue, index) {
      // row是这一行的数据  column 是列的字段信息   cellValue 这个单元格数据   index 索引
      // console.log(row, column, cellValue, index)
      const result = EmployeeEnum.hireType.find(item => item.id === cellValue * 1)
      return result ? result.value : '未知'
    },
    // 删除
    async delRow(id) {
      // 确认框
      try {
        await this.$confirm('确定删除吗?')
      } catch (error) {
        return console.log(error)
      }
      // 删除请求
      await delEmployee(id)
      // 成功操作
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    // 导出选中的数据
    exportCheckData() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: this.formatJson(headers, this.checkArr),
          multiHeader: [['姓名', '基本信息', '', '', '', '', '部门']],
          merges: ['B1:F1', 'A1:A2', 'G1:G2'],
          filename: '员工信息表-部分',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 导出数据
    exportData() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1. 获取导出的全部数据
        const { rows } = await getEmployeeList({
          page: 1, // 页码
          size: 20000 // 每页数量
        })
        // excel 加载的模块
        // 参数说明：
        // multiHeader = [],  // 复杂表头
        // =====> header,  // 表头
        // =====> data,  // 表格的数据
        // =====> filename, // 文件的名称
        // =====> merges = [],  // 合并的规则,复杂表头的情况下会使用
        // =====> autoWidth = true,  // 是否自动宽度
        // =====> bookType = 'xlsx'  // 导出的类型
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: this.formatJson(headers, rows),
          multiHeader: [['姓名', '基本信息', '', '', '', '', '部门']],
          merges: ['B1:F1', 'A1:A2', 'G1:G2'],
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 格式化处理表格的数据
    formatJson(headers, data) {
      // headers表头，data是要处理的数据
      // const results = []
      // data.forEach(item => {
      //   const arr = []
      //   Object.values(headers).forEach(key => {
      //     arr.push(item[key]) //  // key 英文
      //   })
      //   results.push(arr)
      // })
      const results = data.map(item => {
        return Object.values(headers).map(key => {
          if (key === 'timeOfEntry' || key === 'correctionTime') { // 入职时间和转正时间
            return ((new Date(item[key])).toLocaleDateString())
          } else if (key === 'formOfEmployment') { // 聘用形式
            const row = EmployeeEnum.hireType.find(val => val.id === item[key] * 1)
            return row ? row.value : '未知'
          }
          return item[key]
        })
      })
      return results
    },
    // 显示二维码
    showImg(val) {
      if (!val || !val.trim()) return this.$message.warning('暂无图片')
      this.showCode = true
      this.$nextTick(() => {
        QRCode.toCanvas(this.$refs.canvas, val)
      })
    },
    // 显示员工授权角色弹框
    async showDialogSetting(val) {
      await this.$refs['assgin-role'].getUserDetailById(val.id)
      this.$refs['assgin-role'].showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
